<template>
    <div class="loginBox">
        <el-card class="box-card">
            <div class="welcome">
                Welcome!
            </div>
            <el-form :model="regForm" :rules="rules" ref="ruleFormRef" label-width="70px">
                <el-form-item label="账号" prop="account">
                    <el-input v-model="regForm.account" maxlength="20" size="large" placeholder="请输入账号"
                        suffix-icon="el-icon-user-solid"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="regForm.password" maxlength="20" size="large" placeholder="请输入密码"
                        suffix-icon="el-icon-key"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submit(ruleFormRef)" class="regBtn" size="large"
                        :loading="loading">登录
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { login } from '@/api/api'
import { ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const router = useRouter()

let loading = ref(false)

let regForm = reactive({
    account: '',
    password: '',
})

// 表单验证
const rules = reactive<FormRules>({
    account: [
        { required: true, message: '请输入账号', trigger: 'change' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'change' }
    ]
})

const submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            console.log(regForm)
            let formData = {
                ...regForm
            }
            // 新增账号
            login(formData).then((res: any) => {
                if (res.code === 200) {
                    ElMessage.success('登录成功')
                    router.push({
                        name: 'index'
                    })
                } else {
                    ElMessage.error('登录失败')
                }
            }).finally(() => {
                loading.value = false
            })
        }
    })
}

</script>

<style lang="scss" scoped>
.box-card {
    padding: 20px;
    width: 500px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .welcome {
        font-size: 60px;
        margin-bottom: 30px;
        text-align: center;
    }

    .regBtn {
        width: 100%;
    }
}
</style>